package com.chongyahhh.security.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.chongyahhh.security.bean.model.BaseResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



/**
 * @Author chongyahhh
 * 对已认证无权限用户的异常处理
 */
@Component
public class JsonAccessDeniedHandler implements AccessDeniedHandler {
    private final String NO_PERMISSION = "无权限";

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().print(JSONObject.toJSONString(new BaseResult<String>(NO_PERMISSION, false, null)));
    }
}
